﻿# -*- coding: utf-8 -*-
import sys  
reload(sys)
sys.setdefaultencoding('utf8')  
import string
import cgi
import urllib
import datetime
import random
import re

from django.utils import simplejson as json
from sgmllib import SGMLParser, SGMLParseError
from google.appengine.ext import db
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from tweepy import *

consumer_key = "c99OpyISaGpmt3zbUpVvQ"
consumer_secret = "64jP2YW6MkWuMPNnWQXs9qh5DMc5YeIIybG5I02hI"
oauth_token = " "
oauth_verifier = " "

StartUrl = "/API/"
SearchUrl = "/API/search.json"
TwitterUrl = "https://api.twitter.com/1/"
TwitterSearchUrl = "http://search.twitter.com/"

DMGetStartUrl = "/API/direct_messages"
DMGetSentUrl = "/API/direct_messages/sent"
DMGetSpecifiedUrl = "/API/direct_messages/"

TweetsUpdateUrl = "/statuses/update"
RetweetUrl = "/statuses/retweet/"
DelTweetUrl = "/statuses/destroy/"
PostDMUrl = "/direct_messages/new"
DelDMUrl = "/direct_messages/destroy/"
FriendCreateUrl = "/friendships/create"
FriendDelUrl = "/friendships/destroy"
FriendUpdateUrl = "/friendships/update"
FavCreateUrl = "/favorites/create/"
FavDelUrl = "/favorites/destroy/"
ListMemberDelUrl = "/lists/members/destroy"
ListMemberAddUrl = "/lists/members/create"
ListDelUrl = "/lists/destroy"
ListCreateUrl = "/lists/create"
ListUpdateUrl = "/lists/update"
ListSubCreate = "/lists/subscribers/create"
ListSubDel = "/lists/subscribers/destroy"
SearchCreateUrl = "/saved_searches/create"
SearchDelUrl = "/saved_searches/destroy/"

class UserToken(db.Model):
	username = db.StringProperty(required=True)
	usernumber = db.StringProperty(required=True)
	oauth_token = db.StringProperty(required=True)
	oauth_verifier = db.StringProperty(required=True)
	access_token_key = db.StringProperty(required=True)
	access_token_secret = db.StringProperty(required=True)
	consumer_key = db.StringProperty(required=False)
	consumer_secret = db.StringProperty(required=False)
	createdtime = db.DateTimeProperty(required=True, auto_now_add=True)

class LastTweet(db.Model):
	username = db.StringProperty(required=False)
	tweetid = db.IntegerProperty(required=True)
	lastuserid = db.StringProperty(required=True)

class TwitterBot(webapp.RequestHandler):
	def __init__(self):
		self.apikey = consumer_key
		self.apisecret = consumer_secret
		self.try_error = False
		self.try_times = 5
	def get(self, callurl):
		usernum = '143420427'
		UserObjGQL = UserToken.gql("WHERE usernumber = :1", usernum)
		UserObj = UserObjGQL.get()
		TweetObjGQL = LastTweet.gql("WHERE lastuserid = :1", usernum)
		TweetObj = TweetObjGQL.get()
		if UserObj != None:
			self.apikey = UserObj.consumer_key
			self.apisecret = UserObj.consumer_secret
			auth = OAuthHandler(self.apikey, self.apisecret)
			auth.set_access_token(UserObj.access_token_key.decode("utf-8"), UserObj.access_token_secret.decode("utf-8"))
			api = API(auth, 'api.twitter.com', 'search.twitter.com', None, True)
		else:
			self.response.out.write("User:"+ usernum + "Not Oauth yet!<br />")
			return
		if TweetObj != None:
			(s,statuscontent) = api.home_timeline(count = 60, since_id = TweetObj.tweetid)
		else:
			(s,statuscontent) = api.home_timeline(count = 30)
		tweets = json.loads(statuscontent)
		tweetcount = 0
		for val in tweets:
			if tweetcount == 0 and TweetObj != None:
				TweetObj.tweetid = val["id"]
				TweetObj.username = val["user"]["screen_name"]
				TweetObj.put()
			elif tweetcount == 0:
				TweetObj = LastTweet(username = val["user"]["screen_name"], tweetid = val["id"], lastuserid = usernum)
				TweetObj.put()
			tweetcount += 1
			if val["text"].find('星座') != -1 or val["text"].find('@aiww') != -1 or val["text"].find('我有個雞') != -1 or val["text"].find('@___Hooooong___') != -1 or val["text"].find('@ichinesetweets') != -1 or val["text"].find('韓飯') != -1 or val["text"].find('西卡') != -1:
				continue
			if val["text"].find('hangen') != -1 or val["text"].find('韩庚') != -1 or val["text"].find('唯色') != -1 or val["text"].find('Astrology') != -1 or val["text"].find('degewa') != -1 or val["text"].find('藏人') != -1 or val["text"].find('HanGen') != -1:
				continue
			if val["source"].find('Bit Coin') != -1:
				continue
			tweetid = '0'
			pos = val["text"].rfind('RT @')
			if pos != -1:
				contentstr = val["text"][pos+4:]
				m = re.search(r"(\w+):?(.*)", contentstr)
				if m != None:
					author = m.group(1)
					realtweet = m.group(2).strip()
					if realtweet != '' or realtweet != None:
						try:
							(s,statuscontent) = api.user_timeline(screen_name = author, count = 40)
						except:
							statuscontent = None
							pass
						if statuscontent != None:
							#self.response.out.write(statuscontent)
							#self.response.out.write("<br />")
							usrtweets = json.loads(statuscontent)
							for val2 in usrtweets:
								val2["text"]= val2["text"].strip()
								if val2["text"].startswith(realtweet[:20]):
									#self.response.out.write(val2["text"])
									len1 = len(unicode(val2["text"].decode('utf-8')))
									len2 = len(re.sub(ur"[\u4e00-\u9fa5]",'aa',val2["text"]))
									chnnum = len2 - len1
									if chnnum > len1/3:
										tweetid = val2["id"]
									break
			else:
				tweetid = val["id"]
			#self.response.out.write(tweetid)
			#self.response.out.write("<br />")
			#self.response.out.write(val["text"])
			#self.response.out.write("<br />")
			if tweetid != '0':
				(s,statuscontent) = api.get_status(id = tweetid)
				tweets = json.loads(statuscontent)
				try:
					api.retweet(tweetid)
				except:
					pass
				#self.response.out.write(tweets["text"])
				self.response.out.write("<br />")
				#self.response.out.write(len1)
				#self.response.out.write("<br />")
				#self.response.out.write(len2)
				#self.response.out.write("<br />")
			else:
				self.response.out.write('Not found')
				self.response.out.write("<br />")
			self.response.out.write("tweetcount:%d" % tweetcount)
			self.response.out.write("<br />")
		return

application = webapp.WSGIApplication(
																		 [(r'/twibot(.*)', TwitterBot)],
																		 debug=True)

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()